<template>
  <div class="app-container">
    <el-form inline class="form-container">
      <el-form-item>
        <el-date-picker
          v-model="dateRange"
          type="datetimerange"
          :picker-options="pickerOptions"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          align="right"
          value-format="YYYY-MM-DD HH:mm:ss"
          style="width: 250px;"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="handleQuery">筛选</el-button>
        <el-button type="primary" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 图表部分 -->
    <div class="charts-container">
      <div
          v-for="(sensNo, index) in sensNoList"
          :key="sensNo"
          :id="'chart-' + index"
          class="chart"
      ></div>
    </div>

    <el-table
      ref="DetailRef"
      v-loading="loading"
      :data="DetailList"
      @selection-change="handleSelectionChange"
      style="width: 100%; border: 1px solid #ebeef5;"
      :header-cell-style="headerCellStyle"
      stripe
      max-height="62vh"
    >
      <el-table-column width="80" align="center">
        <template v-slot:default="{ $index }">
          {{ $index + 1 }}
        </template>
      </el-table-column>

      <el-table-column prop="warContent" align="center" label="预警信息"></el-table-column>
      <el-table-column prop="ruleScene" align="center" label="规格场景"></el-table-column>
      <el-table-column prop="normalValue" align="center" label="正常值"></el-table-column>
      <el-table-column prop="warningValue" align="center" label="报警值"></el-table-column>
      <el-table-column prop="severity" align="center" label="运行状态"></el-table-column>
      <el-table-column prop="actualValue" align="center" label="实际值"></el-table-column>
    </el-table>

    <el-form>
      <el-form-item class="pagination-container">
        <span>共{{ total }}条记录 第{{ pageSet.pageNum }}/{{ totalPages }}页</span>
        <el-button type="primary" :disabled="pageSet.pageNum === 1" @click="goToFirstPage">首页</el-button>
        <el-button type="primary" :disabled="pageSet.pageNum === 1" @click="goToPreviousPage">上一页</el-button>
        <el-button type="primary" :disabled="pageSet.pageNum === totalPages" @click="goToNextPage">下一页</el-button>
        <el-button type="primary" :disabled="pageSet.pageNum === totalPages" @click="goToLastPage">尾页</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import axios from 'axios';
import * as echarts from 'echarts';
// 设置 axios 的 baseURL
axios.defaults.baseURL = 'http://localhost:8080';

export default {
  name: 'detailPage',
  data() {
    return {
      dateRange: [], // 时间范围
      total: 0, // 总记录数
      loading: false, // 加载状态
      DetailList: [], // 表格数据
      sensNoList: [], // 用于存储所有的 sensNo
      startTimeList: [], // 用于存储所有的 startTime
      warContentList: [], //用于存储所有的warContent
      chartData: { // 图表数据
        xAxis: [],
        series: []
      },
      pageSet: {
        pageNum: 1,
        pageSize: 10
      },
      pickerOptions: {
        shortcuts: [
          {
            text: '最近一周',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setDate(start.getDate() - 7);
              picker.$emit('pick', [start, end]);
            }
          },
          {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setMonth(start.getMonth() - 1);
              picker.$emit('pick', [start, end]);
            }
          },
          {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setMonth(start.getMonth() - 3);
              picker.$emit('pick', [start, end]);
            }
          }
        ]
      },
    };
  },
  methods: {
    headerCellStyle({columnIndex}) {
      return {
        borderLeft: columnIndex !== 0 ? '1px solid #ebeef5' : 'none',
        fontFamily: 'PingFang SC',
        fontSize: '14px',
        color: '#7B828E'
      };
    },

    async handleQuery() {
      this.pageSet.pageNum = 1;
      await this.getAllList()
    },

    async resetQuery() {
      this.dateRange = [];
      await this.getAllList()
    },

    async getAllList() {
      this.DetailList = []; // 清空表格数据
      this.total = 0; // 清空总数

      const allData = [];

      // 使用 for...of 确保异步调用按顺序执行
      for (let sensNo of this.sensNoList) {
        const data = await this.getList(sensNo);
        allData.push(...data); // 将数据追加到 allData 中
      }

      // 对获取到的所有数据进行分页处理
      this.total = allData.length;
      this.DetailList = allData.slice((this.pageSet.pageNum - 1) * this.pageSet.pageSize, this.pageSet.pageNum * this.pageSet.pageSize);
    },

    async getList(sensNo) {
      const [startTime, endTime] = this.dateRange;

      try {
        const response = await axios.post('/api/warning/getDetailData', {
          startTime: startTime || null,
          endTime: endTime || null,
          sensNo: sensNo || null,
        });

        const data = response.data.rows || [];
        return data;

      } catch (error) {
        console.error('获取数据失败:', error);
        return [];
      } finally {
        this.loading = false;
      }
    },


    async getChartData(sensNo, startTime, warContent, index) {
      try {
        const response = await axios.post('/api/detail/detailChart', {
          sensNo: sensNo,
          startTime: startTime
        });
        const chartData = response.data || [];
        this.renderChart(chartData, warContent, index);
      } catch (error) {
        console.error('获取图表数据失败:', error);
      }
    },

    renderChart(chartData, warContent, index) {
      const chart = echarts.init(document.getElementById('chart-' + index));

      const option = {
        backgroundColor: '#0f1c2b',
        title: {
          text: warContent,  // 根据索引动态显示
          left: 'center',
          top: 20,
          textStyle: {
            color: '#ffffff',
            fontSize: 18
          }
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'line',
            lineStyle: {
              color: '#ffffff',
              width: 2
            }
          },
          backgroundColor: 'rgba(0, 0, 0, 0.7)',
          textStyle: {
            color: '#ffffff'
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: chartData.map(item => item.createtime),
          axisLine: {
            lineStyle: {
              color: '#396394'
            }
          },
          axisLabel: {
            color: '#ffffff'
          }
        },
        yAxis: {
          type: 'value',
          axisLine: {
            lineStyle: {
              color: '#396394'
            }
          },
          axisLabel: {
            color: '#ffffff'
          },
          splitLine: {
            lineStyle: {
              color: '#2c3c4c'
            }
          }
        },
        series: [{
          name: '行程',
          type: 'line',
          data: chartData.map(item => item.measureValue),
          lineStyle: {
            color: '#3aa1ff',
            width: 2
          },
          itemStyle: {
            color: '#3aa1ff',
            borderColor: '#ffffff',
            borderWidth: 2
          },
          areaStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
              offset: 0,
              color: 'rgba(58, 161, 255, 0.3)'
            }, {
              offset: 1,
              color: 'rgba(58, 161, 255, 0)'
            }])
          }
        }]
      };

      chart.setOption(option);
    },

    async getAllChart() {
      for (let i = 0; i < this.sensNoList.length; i++) {
        const sensNo = this.sensNoList[i];
        const startTime = this.startTimeList[i] || 'N/A';
        const warContent = this.warContentList[i];
        await this.getChartData(sensNo, startTime, warContent, i);
      }
    },

    handleSelectionChange(selection) {
      this.selectedItems = selection.map(item => item.id);
    },

    goToPreviousPage() {
      if (this.pageSet.pageNum > 1) {
        this.pageSet.pageNum--;
        this.getAllList()
      }
    },

    goToFirstPage() {
      this.pageSet.pageNum = 1;
      this.getAllList()
    },

    goToNextPage() {
      if (this.pageSet.pageNum < this.totalPages) {
        this.pageSet.pageNum++;
        this.getAllList()
      }
    },

    goToLastPage() {
      this.pageSet.pageNum = this.totalPages;
      this.getAllList()
    },
  },
    computed: {
      totalPages() {
        return Math.ceil(this.total / this.pageSet.pageSize);
      }
    },
  mounted() {
    const selectedItems = this.$route.query.selectedItems
        ? JSON.parse(this.$route.query.selectedItems)
        : [];

    if (selectedItems.length > 0) {
      this.sensNoList = selectedItems.map(item => item.sensNo); // 提取所有 sensNo
      this.startTimeList = selectedItems.map(item => item.startTime); // 提取所有 startTime
      this.warContentList = selectedItems.map(item => item.warContent); // 提取所有 warContent
    } else {
      console.error('selectedItems is empty or undefined');
    }
    console.log("start get list\n");
    this.getAllList();
    console.log("end get list\n");
    console.log("start get chart\n");
    this.getAllChart();
    console.log("end get chart\n");
  },
};
</script>

<style scoped>
.app-container {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  height: 100%;
}

.charts-container {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  margin-bottom: 20px;
}

.chart {
  width: 30%; /* 根据需求调整宽度 */
  height: 400px;
  margin-bottom: 20px; /* 根据需求调整间距 */
}

.pagination-container {
  text-align: right;
  width: 100%;
  margin-top: 20px;
}

.pagination-container > * {
  display: inline-block;
}
</style>
